package com.ibpd.henuocms.web.controller.manage;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ibpd.dao.impl.ServiceProxyFactory;
import com.ibpd.henuocms.common.TemplateUtil;
import com.ibpd.henuocms.entity.NodeEntity;
import com.ibpd.henuocms.entity.PageTemplateEntity;
import com.ibpd.henuocms.entity.StyleTemplateEntity;
import com.ibpd.henuocms.entity.ext.PageTemplateExtEntity;
import com.ibpd.henuocms.service.node.INodeService;
import com.ibpd.henuocms.service.node.NodeServiceImpl;
import com.ibpd.henuocms.service.pageTemplate.IPageTemplateService;
import com.ibpd.henuocms.service.pageTemplate.PageTemplateServiceImpl;
import com.ibpd.henuocms.service.styleTemplate.IStyleTemplateService;
import com.ibpd.henuocms.service.styleTemplate.StyleTemplateServiceImpl;
import com.ibpd.henuocms.web.controller.ext.FormModel;

@Controller
public class NodeTemplate extends BaseController {
	Logger log=Logger.getLogger(NodeTemplate.class);
	@RequestMapping("Manage/NodeTemplate/index.do")
	public String index(String id,String type,org.springframework.ui.Model model) throws IOException{
		model.addAttribute("nodeId",id);
//		String[] ss=id.split("_");
//		if(ss.length==2){
//			if(StringUtil.isNumeric(ss[1])){
//				Long siteId=Long.parseLong(ss[1]);
//				model.addAttribute("siteId",siteId);
//			}
//		}else{
//			if(StringUtil.isNumeric(id)){
//				Long nodeId=Long.parseLong(ss[1]);
//				model.addAttribute("nodeId",nodeId);
//			}
//
//		}
		
		return "manage/nodeTemplate/index";
	}	 
	@RequestMapping("Manage/NodeTemplate/toAdd.do")
	public String toAdd(String nodeId,org.springframework.ui.Model model) throws IOException{
		model.addAttribute("nodeId",nodeId);
		return "manage/nodeTemplate/add";
	}	@RequestMapping("Manage/NodeTemplate/test.do")
	public void test() throws IOException{
		TemplateUtil.makeNewPageTemplate(1);
	}
	
	@RequestMapping("Manage/NodeTemplate/doAdd.do")
	public void doAdd(String siteOrNodeId,PageTemplateEntity pageTemplate,HttpServletResponse response) throws IOException{
		if(StringUtils.isEmpty(siteOrNodeId)){
			super.printMsg(response, "-1", "-1", "参数错误\n未找到参数nodeId的值");
		}else{
			String[] ss=siteOrNodeId.split("_");
			Long siteId=-1L;
			Long nId=-1L;
			if(ss.length==2){
				if(StringUtil.isNumeric(ss[1])){
					siteId=Long.parseLong(ss[1]);
				}
			}else{
				if(StringUtil.isNumeric(siteOrNodeId)){
					nId=Long.parseLong(siteOrNodeId);
				}
			}
			
			if(siteId!=-1L){
				pageTemplate.setSubSiteId(siteId);
			}else if(nId!=-1L){
				INodeService nodeService=(INodeService) getService(NodeServiceImpl.class);
				NodeEntity ne=nodeService.getEntityById(nId);
				pageTemplate.setNodeId(nId);
				pageTemplate.setSubSiteId(ne.getSubSiteId());
			}
			pageTemplate.setIsDefault(false);
			
			IPageTemplateService ps=(IPageTemplateService) getService(PageTemplateServiceImpl.class);
			ps.saveEntity(pageTemplate);
			
			super.printMsg(response, "99", pageTemplate.getId().toString(), "保存成功.");
		}
		
	}
	@RequestMapping("Manage/NodeTemplate/toEditContent.do")
	public String toEditContent(Long pageTemplateId,org.springframework.ui.Model model) throws IOException{
		model.addAttribute("pageTemplateId",pageTemplateId);
		IPageTemplateService pt=(IPageTemplateService) getService(PageTemplateServiceImpl.class);
		PageTemplateEntity page=pt.getEntityById(pageTemplateId);
		if(page!=null){
			model.addAttribute("templatePath",TemplateUtil.getTemplateFileUrlPath(page.getTemplateFilePath()));
			String content=TemplateUtil.getTemplateContent(page.getTemplateFilePath(),"index.jsp");
			model.addAttribute("content",content);
		}
		return "manage/nodeTemplate/editContent";
	}
	@RequestMapping("Manage/NodeTemplate/toEditStyle.do")
	public String toEditStyle(Long pageTemplateId,org.springframework.ui.Model model){
		model.addAttribute("pageTemplateId",pageTemplateId);
		IPageTemplateService pt=(IPageTemplateService) getService(PageTemplateServiceImpl.class);
		PageTemplateEntity page=pt.getEntityById(pageTemplateId);
		if(page!=null){
			IStyleTemplateService st=(IStyleTemplateService) getService(StyleTemplateServiceImpl.class);
			StyleTemplateEntity ste=st.getEntityById(page.getDefaultStyleTemplateId());
			String content="";
			if(ste!=null){
				model.addAttribute("styleTemplateId",ste.getId());
				content=TemplateUtil.getTemplateContent(ste.getTemplateFilePath(),"style.css");
			}else{
				model.addAttribute("styleTemplateId","-1");
				content="body{}";
			}
			model.addAttribute("content",content);
		}
		return "manage/nodeTemplate/editStyle";

	}
	@RequestMapping("Manage/NodeTemplate/toNewStyle.do")
	public String toNewStyle(Long pageTemplateId,org.springframework.ui.Model model) throws IOException{
		model.addAttribute("pageTemplateId",pageTemplateId);
		model.addAttribute("styleTemplateId","-1");
		model.addAttribute("content","body{}");
		return "manage/nodeTemplate/editStyle";
	}
	@RequestMapping("Manage/NodeTemplate/doEditStyle.do")
	public void doEditStyle(Long pageTemplateId,Long styleTemplateId,String content,HttpServletResponse response) throws IOException{
			IStyleTemplateService st=(IStyleTemplateService) getService(StyleTemplateServiceImpl.class);
			StyleTemplateEntity ste=st.getEntityById(styleTemplateId);
			if(ste!=null){
				TemplateUtil.saveTemplateContent(ste.getTemplateFilePath(), "style.css",content);
				super.printMsg(response, "99", "99", "保存成功");
			}else{
				IPageTemplateService pt=(IPageTemplateService) getService(PageTemplateServiceImpl.class);
				PageTemplateEntity page=pt.getEntityById(pageTemplateId);
				if(page==null){
					super.printMsg(response, "-1", "-1", "pageTempalte为空");return ;
				}
				String dir=TemplateUtil.makeNewStyleTemplate();
				TemplateUtil.saveTemplateContent(dir, "style.css", content);
				StyleTemplateEntity se=new StyleTemplateEntity();
				se.setCreateDate(new Date());
				se.setTemplateFilePath(dir);
				se.setSubSiteId(page.getSubSiteId());
				se.setTitle(page.getTitle()+"的样式模板");
				st.saveEntity(se);
				pt.setStyleTempateId(page.getId(), se.getId());
//				page.setDefaultStyleTemplateId(se.getId());
//				pt.saveEntity(page);
				super.printMsg(response, "99", "99", "保存成功");
			}

	}
	@RequestMapping("Manage/NodeTemplate/doEditContent.do")
	public void doEditContent(Long pageTemplateId,String content,HttpServletResponse response) throws IOException{
		IPageTemplateService pt=(IPageTemplateService) getService(PageTemplateServiceImpl.class);
		PageTemplateEntity page=pt.getEntityById(pageTemplateId);
		if(page!=null){
			TemplateUtil.saveTemplateContent(page.getTemplateFilePath(), "index.jsp",content);
			super.printMsg(response, "99", "99", "保存成功");
		}else{
			super.printMsg(response, "-1", "-1", "没有这个模板");
		}
		
	}
	@RequestMapping("Manage/NodeTemplate/toEditBase.do")
	public String toEditBase(Long pageTemplateId,org.springframework.ui.Model model) throws IOException{
		IPageTemplateService ts=(IPageTemplateService) getService(PageTemplateServiceImpl.class);
		PageTemplateEntity pt=ts.getEntityById(pageTemplateId);
		model.addAttribute("pageTemplate",pt);
		return "manage/nodeTemplate/toEditBase";
	}
	@RequestMapping("Manage/NodeTemplate/doEditBase.do")
	public void doEditBase(PageTemplateEntity pageTemplate,HttpServletResponse response) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(pageTemplate!=null){
			if(pageTemplate.getId()!=null && pageTemplate.getId()!=-1L){
				IPageTemplateService ts=(IPageTemplateService) getService(PageTemplateServiceImpl.class);
//				PageTemplateEntity pt=ts.getEntityById(pageTemplate.getId());
//				if(pt!=null){
////					swap(pt,pageTemplate);
//					pt.setTitle(pageTemplate.getTitle());
//					pt.setOrder(pageTemplate.getOrder());
//					pt.setGroup(pageTemplate.getGroup());
//					pt.setUseMouseRightKey(pageTemplate.getUseMouseRightKey());
//					pt.setUseDarkColor(pageTemplate.getUseDarkColor());
//					pt.setEnableCopyPageContent(pageTemplate.getEnableCopyPageContent());
//					pt.setLastUpdateDate(new Date());
//					ts.getDao().clearCache();
//					ts.saveEntity(pt);
					ts.savePageTemplate(pageTemplate);
					super.printMsg(response, "99", "99", "保存成功");
//				}else{
//					super.printMsg(response, "-1", "-1", "没有这个模板");
//				}
			}else{
				super.printMsg(response, "-2", "-2", "参数错误-没有ID");
			}
		}else{
			super.printMsg(response, "-3", "-3", "参数错误没有传递数据");
		}
	}
	@RequestMapping("Manage/NodeTemplate/doDelete.do")
	public void doDelete(String ids,HttpServletResponse response) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		String id[]=ids.split(",");
		String usedIds="";
		IPageTemplateService ps=(IPageTemplateService) getService(PageTemplateServiceImpl.class);
			for(String d:id){
			if(StringUtil.isNumeric(d)){
				Long pId=Long.parseLong(d);
				if(ps.checkPageTempIsUsed(pId)){
					usedIds=usedIds+pId+",";
				}
			}
		}
		if(StringUtils.isEmpty(usedIds)){
			ps.batchDel(ids);	
			super.printMsg(response, "99", "99", "删除成功");
		}else{
			super.printMsg(response, "-1", "-1", "以下ID的模板正在被使用,无法删除:"+usedIds);
		}
	}	
//	private IBaseEntity swap(IBaseEntity dbEntity , IBaseEntity obEntity) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
//		Method[] methods=obEntity.getClass().getMethods();
//		for(Method getMethod:methods){
//			String getMethodName=getMethod.getName();
//			if(getMethodName.substring(0,3).equals("get") && !getMethodName.equals("getClass") && !getMethodName.equals("getCreateDate") && !getMethodName.equals("getSubSiteId")){
//				String setMethodName="set"+getMethodName.substring(3);
//				Method setMethod=dbEntity.getClass().getMethod(setMethodName, getMethod.getReturnType());
//				if(setMethod!=null){
//					
//					setMethod.invoke(dbEntity, getMethod.invoke(obEntity, null));
//				}
//			}
//		}
//		return dbEntity;
//	}

	@RequestMapping("Manage/NodeTemplate/saveProp.do")
	public void saveProps(Long id,String field,String value,HttpServletResponse resp) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(id!=null && id!=-1){
			IPageTemplateService ps=(IPageTemplateService) ServiceProxyFactory.getServiceProxy(PageTemplateServiceImpl.class);
			PageTemplateEntity cnt=ps.getEntityById(id);
			if(cnt!=null){
				//先确定参数类型
				Method tmpMethod=cnt.getClass().getMethod("get"+field.substring(0,1).toUpperCase()+field.substring(1), new Class[]{});
				Method method=cnt.getClass().getMethod("set"+field.substring(0,1).toUpperCase()+field.substring(1), new Class[]{tmpMethod.getReturnType()});
				Object val=getValue(value,tmpMethod.getReturnType().getSimpleName());
				String path=cnt.getTemplateFilePath();
				method.invoke(cnt, val);
				cnt.setTemplateFilePath(path);
				ps.saveEntity(cnt);
			}
		}
	}
	@RequestMapping("Manage/NodeTemplate/props.do")
	public String props(Long pageTemplateId,org.springframework.ui.Model model) throws IOException{
		model.addAttribute("pageTemplateId",pageTemplateId);
		IPageTemplateService ps=(IPageTemplateService) getService(PageTemplateServiceImpl.class);
		PageTemplateEntity pt=ps.getEntityById(pageTemplateId);
		model.addAttribute("pageTemplate",pt);
		return "manage/nodeTemplate/props";
	}	 
	@RequestMapping("Manage/NodeTemplate/init.do")
	public void init(HttpServletResponse resp) throws IOException{
		IPageTemplateService templateService=(IPageTemplateService) this.getService(PageTemplateServiceImpl.class);
		templateService.init();
		this.printMsg(resp, "100", "100", "ok");
	}
	@RequestMapping("Manage/NodeTemplate/list.do")
	public void getList(HttpServletRequest req,HttpServletResponse resp,String nodeId,String order,Integer page,Integer rows,String sort) throws IOException{
		if(StringUtils.isEmpty(nodeId))
			return;
		Long nId=null;
		Long[] siteIds=null;
		String[] ss=nodeId.split("_");
		if(ss.length==2){ 
			if(StringUtil.isNumeric(ss[1])){
				siteIds=new Long[]{Long.parseLong(ss[1])};
			}
		}else{
			if(StringUtil.isNumeric(nodeId)){
				nId=Long.parseLong(nodeId);
			}
		}
		IPageTemplateService pageService=(IPageTemplateService) this.getService(PageTemplateServiceImpl.class);
		//这里的取值顺序 ：如果nodeId有值，就优先取node下的模板，否则才去site下的模板
		String  filterString=null;
		order=(sort==null)?null: sort+" "+order;
		List<PageTemplateExtEntity> pageTempList=pageService.getList(siteIds, nId, rows, rows*(page-1)+1, order, filterString);
		Long rowCount=pageService.getRowCount(siteIds, nId,filterString);
		JSONArray json=JSONArray.fromObject(pageTempList);
		super.printJsonData(resp, "{\"total\":"+rowCount.toString()+",\"rows\":"+json.toString()+"}");
	}
}
